<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/10 0010
 * Time: 下午 8:15
 */

namespace app\common\model;

use com\gdl\agk\dataobject\practice\PracticeDTO;
use com\gdl\agk\interfaces\PracticeServiceClient;
use com\gdl\agk\interfaces\UserServiceClient;
use com\gdl\agk\interfaces\CompanyServiceClient;
use com\gdl\agk\dataobject\user\UserRequestDTO;
use think\Db;
use think\Model;
use think\Config;
use think\Session;

class Examsession extends Model
{

    //添加一个考试记录
    public function addExamHistory($sessionid, $companyId = 0, $status = 1,$identity_id=false)
    {
		if($identity_id){  //添加一个额外如果传用户id 就直接查询 
				$exam = $this->where(['identity_id'=>$identity_id])->field('*')->select();
		} else {
			  $exam = $this->getExamSessionBySessionid($sessionid);
		}
      
		
        if (!$exam)
            return false;

        $t = time() - $exam[0]->es_starttime;
        \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk'));
        $userClient = new UserServiceClient(NULL);
        \ApiClient::build($userClient);
        $userRequestDo = new UserRequestDTO();
        $userRequestDo->id = $exam[0]->identity_id;
        if ($companyId) {
            $userRequestDo->field = 'realname';
            $companyClient = new CompanyServiceClient(NULL);
            \ApiClient::build($companyClient);
            $company = $companyClient->getCompanyInfoById($companyId, '', TRUE,$exam[0]->identity_id);
        } else {
            $userRequestDo->field = 'realname,ex_user_company.company_name company';
            $user = $userClient->getUserInfoById($userRequestDo);
        }

        $es_setting = unserialize($exam[0]->es_setting);

        if ($t >= $exam[0]->es_time * 60)
            $t = $exam[0]->es_time * 60;
        $BasicModel = new Basic();
        $basic_name = $BasicModel->getListByArgOne(['id'=>$exam[0]->es_basic],'basic');
        $cc = array(//存入正式考试表数组
            'identity_id' => $exam[0]->identity_id,
            'ep_type' => $exam[0]->es_type,
            'ep_paperId' => $exam[0]->es_key, //考试试卷id
            'ep_paper_name' => $exam[0]->es_papername, //考试试卷名
            'basic_name' => $basic_name['basic'], //考试试卷名
            'question' => $exam[0]->es_question,
            'answer' => $exam[0]->es_useranswer,
            'modified' => $exam[0]->es_score,
            'basicid' => $exam[0]->es_basic,
            'isvalid' => $exam[0]->suspicion==1?0:1,
            'ispass' => $exam[0]->es_score >= $es_setting['p_total_score'] ? 1 : 0,
			'useranswer' => $exam[0]->useranswer,
        );

        if (($exam[0]->es_score >= $es_setting['p_total_score']) && $exam[0]->es_type==1){//模拟考试是否及格 及格加入 练习表
            $addpracticeDo = new PracticeDTO();
           // $TrainingRoom = new TrainingRoom();
           // $trainingId = $TrainingRoom->getTrainingIdBybasicid($exam[0]->es_basic);
            $api_p = new PracticeServiceClient(null);
            \ApiClient::build($api_p);
            $practice_data = [];
            $practice_data['name'] = '4';
            $practice_data['identity_id'] = $exam[0]->identity_id;
            $practice_data['q_question'] = $exam[0]->es_papername;
            $practice_data['scores'] = $es_setting['scores'];
            $practice_data['status'] = 1;
          //  $practice_data['trainingid'] = $trainingId['id']?$trainingId['id']:$_COOKIE['t'];
			$practice_data['trainingid'] = 1;
            $practice_data['practice_time'] = time();
            $practice = serialize(array('data' => $practice_data));
            $addpracticeDo->insert = $practice;
            //添加到练习表
            $a = $api_p->contrast_practice($addpracticeDo);
        }
        $args = array(//info试卷具体内容
            'state' => 1,
            'score' => $exam[0]->es_score,
            'total_score' => $es_setting['p_total_score'],
            'scorelist' => $exam[0]->es_scorelist,
            'passscore' => $es_setting['p_pass_score'],
            'starttime' => $exam[0]->es_starttime,
            'time' => $t,
            'status' => 1,
            'company' => $companyId ? $company->data['name'] : $user->data['company'],
            'name' => $user->data['realname'],
            'modified' => $exam[0]->es_score
        );
        // 简单的直接使用db插入
        Db::startTrans();
        try {
            Db::name('exams_papers')->insert($cc);
            $ehid = Db::name('exams_papers')->getLastInsID();

            $args['paperid'] = $ehid;
            $stae = Db::name('papers_info')->insert($args);

            $ep_infoId = Db::name('papers_info')->getLastInsID();

            $ss = Db::name('exams_papers')->where(['ep_id' => $ehid])->update(['ep_infoId' => $ep_infoId]);
            $this->delExamSession($sessionid,$exam[0]->identity_id);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            return ajax_return_adv_error($e->getMessage());
        }

        return $ehid;
    }

    //清除会话内容
    public function delExamSession($sessionid,$identity_id)
    {
        if(!$sessionid)
            $sessionid = session_id();
        $result = $this->where(['es_id'=>$sessionid])->delete();
        if (empty($result) && $identity_id){
            $result = $this->where(['identity_id'=>$identity_id])->delete();
        }
        return $result;
    }

    public function getExamSessionBySessionid($sessionid,$identity_id=null){
        if(!$sessionid)
            $sessionid = session_id();
        $result =  $this->where(['es_id'=>$sessionid])->field('*')->select();
        if (empty($result) && $identity_id){
            $result = $this->where(['identity_id'=>$identity_id])->field('*')->select();
        }
        return $result;
    }
	
	 public function getExamSessionByIdentityid($identity_id=0,$fiekd='*'){
       
            $result = $this->where(['identity_id'=>$identity_id])->field($fiekd)->select();
        
        return $result;
    }

    /**
     * 设置临时session表中 所有超时考试自动交卷 获取答案为字段es_useranswer
     */
    public function setAllExamSessionEndBasic($companyId){
        $nowTime = time();
        $sql = "SELECT es_id,es_useranswer,es_question,es_setting,es_userid,suspicion FROM `ex_examsession` WHERE es_starttime+es_time*60<".$nowTime."";
        $EndBasicLists = $this->query($sql);
        if ($EndBasicLists){
            $Questype = new \app\common\model\Questype();
            $questypes = $Questype->getQuestypeList();
            foreach ($EndBasicLists as $key=>$EndBasic){
                $needhand = 0;
                $question =  unserialize($EndBasic['es_useranswer']);
                $es_question = unserialize($EndBasic['es_question']);
                $es_setting = unserialize($EndBasic['es_setting']);
                $dw = new \app\common\logic\DrawQuestion();
                $dw_sorc = $dw->deRation($es_setting['p_setting']);
                $scores = [];
                foreach ($dw_sorc as $vs) {
                    $scores[$vs['1']] = [$vs['2'], $vs['3']];
                }
                $p_setting = $scores;

                $questionsList = array(); //试题id集合
                foreach ($es_question['questions'] as $qkey => $qval) {
                    $questionsList[$qval['q_typeid']][] = $qval;
                }
                if (is_null($question))
                    $question = [];
                foreach ($question as $key => $a)
                    $es_useranswer[$key] = $a;
                $questypes = setArrKeyId($questypes);
                foreach ($questionsList as $key => $tmp) {
                    if (!@$questypes[$key]['sort']) {

                        foreach ($tmp as $p) {

                            if (is_array(@$es_useranswer[$p['id']])) {
                                $nanswer = '';
                                $answer = $es_useranswer[$p['id']];
                                asort($answer);
                                $nanswer = implode("", $answer);
                                if ($nanswer == $p['q_answer'])
                                    $score = $p_setting[$key][1];
                                else {
                                    if (@$questypes[$key]['tchoice'] == 3) {
                                        $alen = strlen($p['q_answer']);
                                        $rlen = 0;
                                        foreach ($answer as $t) {
                                            if (strpos($p['q_answer'], $t) === false) {
                                                $rlen = 0;
                                                break;
                                            } else {
                                                $rlen++;
                                            }
                                        }
                                        $score = floatval($p_setting[$key][1] * $rlen / $alen);
                                    } else
                                        $score = 0;
                                }
                            } else {
                                $answer = @$es_useranswer[$p['id']];

                                if ($answer == $p['q_answer']) {
                                    $score = @$p_setting[$key][1];
                                } else
                                    $score = 0;
                            }

                            $scorelist[$p['id']] = $score;
                        }
                        $needhand = 1;
                    }
                    else {
                        if (is_array($tmp) && count($tmp))
                            $needhand = 1;
                    }
                }
                $args['es_useranswer'] = serialize($question); //用户的答案

                $args['es_scorelist'] = serialize($scorelist); //获取所做试题 得分数据

                $args['es_score'] = array_sum($scorelist);
                $args['es_status'] = 2;
                $this->modifyExamSession($args, session_id());
                $id = $this->addExamHistory($EndBasic['es_id'],$companyId, 1);
                if ($id){
                    return true;
                }else{
                    return false;
                }
            }
        }else{
            return false;
        }
    }

    //修改考试会话内容
    //参数：会话内容数组
    //返回值：true
    public function modifyExamSession($args,$sessionid)
    {
        if(!$sessionid)
            $sessionid = session_id();

        $this->where(['es_id'=>$sessionid])->update($args);
        return true;
    }
	
	 //修改考试会话内容 identity_id 版
    //参数：会话内容数组
    //返回值：true
    public function modifyExamSidentityid($args,$identity_id)
    {

        $this->where(['identity_id'=>$identity_id])->update($args);
        return true;
    }

    //增加一个考试会话
    //参数：会话信息数组
    //返回值：true
    public function insertExamSession($args)
    {
		if(!isset($_SESSION)){
			session_start();
		}
        $args['es_id']=session_id();
        $args['es_starttime'] = time();
       // var_dump(session_id());die;
        $this->insert($args);
        return true;
    }


    /**
     * 获取剩余考试时间
     * @param $sessionvars
     * @return int
     */
    public function getexamlefttime($sessionvars){
        $lefttime = 0;

        if($sessionvars[0]['es_status'] == 0 )
        {
            if(time() > ($sessionvars[0]['es_starttime'] + $sessionvars[0]['es_time']*60))
            {
                $lefttime = $sessionvars[0]['es_time']*60;
            }
            else
            {
                $lefttime = time() - $sessionvars[0]['es_starttime'];
            }
        }
        return $lefttime;
    }

    /**
     * 根据试题id集合 返回ids集合 和 以试题类型为键值的试题集合
     * @param $questions
     * @return array [ids集合，以试题类型为键值的试题集合]
     */
    public function getQuestionsByQuestions($questions){
        $qids = array();//试题id集合
        $questionsList = array();//试题id集合
        array_multisort(i_array_column($questions['questions'],'q_typeid'),SORT_ASC,$questions['questions']);
        foreach ($questions['questions'] as $qkey=>$qval){

            $questionsList[$qval['q_typeid']][$qkey]=$qval;
            $qids[$qval['q_typeid']][$qkey]=$qval['id'];
        }
        return [$qids,$questionsList];
    }
	
	 public function getQuestionsByQuestions_code($questions){
        $qids = array();//试题id集合
        $questionsList = array();//试题id集合
        array_multisort(i_array_column($questions['questions'],'q_typeid'),SORT_ASC,$questions['questions']);
        foreach ($questions['questions'] as $qkey=>$qval){
            $questionsList[$qval['q_typeid']][]=$qval;
			$questionsList[$qval['q_typeid']]['code'] = (int)$questionsList[$qval['q_typeid']]['code']+1;
            $qids[$qval['q_typeid']][]=$qval['id'];

        }
        return [$qids,$questionsList];
    }
	
	public function getListByArgOne(array $arg,$field='*')
    {
        return $this->where($arg)->field($field)->find();
    }
}